package com.redshark.wmm.MeasurementProcessing;

import java.util.LinkedList;

public class VoltageProcessor implements MeasurementProcessor {
	private final int NUM_AVERAGE = 10;
	
	private LinkedList<Double> ll = new LinkedList<Double>();
	
	private double runningTotal = 0;
	
	public static double processMeasurement(int ADReading, int channel) {
		double value = AD_CONSTANT * ADReading;

		switch (channel) {
		case 0:
			value *= 2.5785;
			value -= 5.2625;
			break;
		case 1:
			value *= 13.154;
			value -= 26.789;
			break;
		case 2:
			value *= 54.714;
			value -= 111.39;
			break;
		case 3:
			value *= 108.33;
			value -= 218.743;
			break;
		case 4:
			value *= 216.67;
			value -= 437.487;
			break;
		}
		return value;
	}

	@Override
	public Measurement displayMeasurement(int[] data) {
		double d;
		if(data[0] * AD_CONSTANT > 3.2 || data[0] * AD_CONSTANT < .5){
			if(data[1] * AD_CONSTANT > 3.2 || data[1] * AD_CONSTANT < .5){
				if(data[2] * AD_CONSTANT > 3.2 || data[2] * AD_CONSTANT < .5){
					if(data[3] * AD_CONSTANT > 3.2 || data[3] * AD_CONSTANT < .5){
						d = processMeasurement(data[4], 4);
						if(ll.size() > NUM_AVERAGE){
							runningTotal -= ll.removeFirst();
						}
						
						runningTotal += d;
						ll.add(d);
						return new Measurement(runningTotal/ll.size(), 3, "Volts");
					}
					else
					{
						d = processMeasurement(data[3], 3);

						if(ll.size() > NUM_AVERAGE){
							runningTotal -= ll.removeFirst();
						}
						
						runningTotal += d;
						ll.add(d);
						return new Measurement(runningTotal/ll.size(), 3, "Volts");
					}
				}
				else
				{
					d = processMeasurement(data[2], 2);

					if(ll.size() > NUM_AVERAGE){
						runningTotal -= ll.removeFirst();
					}
					
					runningTotal += d;
					ll.add(d);
					return new Measurement(runningTotal/ll.size(), 3, "Volts");
				}
			}
			else
			{
				d = processMeasurement(data[1], 1);

				if(ll.size() > NUM_AVERAGE){
					runningTotal -= ll.removeFirst();
				}
				
				runningTotal += d;
				ll.add(d);
				return new Measurement(runningTotal/ll.size(), 3, "Volts");
			}
		}
		else
		{
			d = processMeasurement(data[0], 0);

			if(ll.size() > NUM_AVERAGE){
				runningTotal -= ll.removeFirst();
			}
			
			runningTotal += d;
			ll.add(d);
			
			double voltage = runningTotal/ll.size();
			
			if(Math.abs(voltage)< .25){
				return new Measurement(voltage*1000, 3, "MilliVolts");
			}
			else{
				return new Measurement(voltage, 3, "Volts");
			}

		}
		

	}

}
